import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jicaimao_flutter/dao/user_info_dao.dart';
import 'package:jicaimao_flutter/views/mine/authentication_state_page.dart';
import 'package:fluttertoast/fluttertoast.dart';

class IdePage extends StatefulWidget {
  @override
  _IdePageState createState() => _IdePageState();
}

class _IdePageState extends State<IdePage> {
  ///
  ///  [_idCardFontImgFile] this is user's IdCard front Photo
  ///  [_idCardBackImgFile] this is user's IdCard back Photo
  ///  [_idCardHandImgFile] user holding your IDCard take a Photo
  ///
  /// [_idCardFontImgServerStr]
  /// [_idCardBackImgServerStr]
  /// [_idCardHandImgServerStr]
  /// 服务器返回对于的图片地址信息
  ///
  File _idCardFontImgFile;
  File _idCardBackImgFile;
  File _idCardHandImgFile;
  String _idCardFontImgServerStr;
  String _idCardBackImgServerStr;
  String _idCardHandImgServerStr;

  ///
  /// 记录用户信息
  ///
  var _tfUserName = "";
  var _tfUserIDCardNumber = "";

  TextEditingController _userNameController;
  TextEditingController _userIDCardNumberController;

  @override
  void initState() {
    // TODO: implement initState
    _userNameController = new TextEditingController();
    _userIDCardNumberController = new TextEditingController();
    super.initState();
  }

  void shoTipToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        iconTheme: IconThemeData(color: Colors.black),
        title: Text(
          '身份证验证',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Stack(
        children: <Widget>[
          SingleChildScrollView(
            child: Column(
              children: <Widget>[
                EditTextWidget(
                  editName: '姓名',
                  hintText: '请输入身份证姓名',
                  labelText: '请输入身份证姓名',
                  distance: 40.0,
                  textInputType: TextInputType.text,
                  controller: _userNameController,
                  onChanged: (String value) => _tfUserName = value,
                ),
                EditTextWidget(
                  editName: '身份证号',
                  hintText: '请输入身份证号码',
                  labelText: '请输入身份证号码',
                  distance: 12.0,
                  textInputType: TextInputType.number,
                  controller: _userIDCardNumberController,
                  onChanged: (String value) => _tfUserIDCardNumber = value,
                ),
                Container(
                  color: Colors.white,
                  margin: EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 0.0),
                  child: Column(
                    children: <Widget>[
                      Container(
                        width: 600.0,
                        height: 40.0,
                        margin: EdgeInsets.fromLTRB(0.0, 6.0, 0.0, 6.0),
                        padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                        color: Colors.white,
                        child: Text(
                          '拍摄您的二代身份证原件，请确保图片清晰，四角完整',
                          style: TextStyle(
                            fontSize: 12.0,
                            color: Color(0xFF999999),
                          ),
                        ),
                      ),
                      ImagePlaceHolder(
                          placeholderAssetStr: 'images/auth_card_back.png',
                          imageFile: _idCardFontImgFile,
                          onTap: () => showSelectBottomDialog(context, 1)),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: ImagePlaceHolder(
                            placeholderAssetStr: 'images/auth_card_front.png',
                            imageFile: _idCardBackImgFile,
                            onTap: () => showSelectBottomDialog(context, 2)),
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 0.0),
                  padding: EdgeInsets.only(top: 5.0),
                  color: Colors.white,
                  child: Column(
                    children: <Widget>[
                      Center(
                        child: Text('本人手持二代身份证原件，请确保图片清晰，四角完整'),
                      ),
                      Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Container(
                          color: Colors.white,
                        ),
                      ),
                      ImagePlaceHolder(
                          placeholderAssetStr: 'images/auth_card_with_user.png',
                          imageFile: _idCardHandImgFile,
                          onTap: () => showSelectBottomDialog(context, 3)),
                      Container(
                        height: 5.0,
                        margin: EdgeInsets.fromLTRB(0.0, 2.0, 0.0, 2.0),
                        padding: EdgeInsets.all(2.0),
                        color: Colors.white,
                      ),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 0.0),
                  color: Colors.white,
                  padding: EdgeInsets.only(top: 8.0),
                  child: Column(
                    children: <Widget>[
                      Center(
                        child: Text(
                          '拍摄照片要求',
                          style: TextStyle(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.fromLTRB(15.0, 2.0, 15.0, 2.0),
                        margin: EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 4.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text('请确保您上传的身份证照片是真实有效'),
                            Padding(padding: EdgeInsets.only(top: 8.0)),
                            Text('请确保您图片的信息清晰可见'),
                            Padding(padding: EdgeInsets.only(top: 8.0)),
                            Text('请确保您上传的图片没有反光或折痕情况'),
                            Padding(padding: EdgeInsets.only(top: 8.0)),
                            Text('请确保您上传的图片为彩色图像'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(15.0, 2.0, 15.0, 2.0),
                  margin: EdgeInsets.fromLTRB(0.0, 4.0, 0.0, 60.0),
                  child: Text(
                    '为确保交您的账户安全，保障您的合法权益，请您完成身份验证！我们提供安全高效实时联网的官方身份认证服务，具有更高级别的安全保证。身份验证一旦成功，不予修改和解除认证。建议您谨慎选择，真实填写。',
                    style: TextStyle(fontSize: 11.0, color: Color(0xFF999999)),
                  ),
                )
              ],
            ),
          ),
        ],
      ),
      bottomSheet: GestureDetector(
        onTap: () {
//          print('ll$_tfUserName');
          if (_tfUserName.isEmpty || _tfUserIDCardNumber.isEmpty) {
            shoTipToast('姓名或账户为空');
            return;
          }
          if (_idCardFontImgServerStr.isEmpty ||
              _idCardBackImgServerStr.isEmpty ||
              _idCardHandImgServerStr.isEmpty) {
            shoTipToast('用户身份证信息为空!');
            return;
          }

          ///请求网络
          UserInfoDao.uploadToServerIdentifyInfo(
                  _tfUserName.trim(),
                  _tfUserIDCardNumber.trim(),
                  _idCardFontImgServerStr,
                  _idCardBackImgServerStr,
                  _idCardHandImgServerStr)
              .then((res) {
            if (res != null && res.result) {
              Future.delayed(const Duration(seconds: 1), () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => AuthenticationIngSatePage()),
                );
              });
            }
          });
        },
        child: Container(
            alignment: Alignment.center,
            height: 40.0,
            color: Color(0xFFB969FF),
            child: Text(
              '确认提交',
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            )),
      ),
    );
  }

  ///
  ///
  /// 选择照片
  ///
  void showSelectBottomDialog(BuildContext context, int type) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 200.0,
            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(5.0),
                  color: Colors.white,
                  alignment: Alignment.center,
                  child: Text(
                    '请选择',
                    style: TextStyle(color: Colors.black, fontSize: 18.0),
                  ),
                  height: 40.0,
                ),
                CommonItemSelect(
                  onTabItem: () {
                    Navigator.pop(context);
                    _getImage(ImageSource.camera, type);
                  },
                  title: '拍照',
                  itemHeight: 50.0,
                ),
                CommonItemSelect(
                  onTabItem: () {
                    Navigator.pop(context);
                    _getImage(ImageSource.gallery, type);
                  },
                  title: '相册',
                  itemHeight: 50.0,
                ),
                CommonItemSelect(
                  title: '取消',
                  itemHeight: 50.0,
                  color: Colors.grey,
                )
              ],
            ),
          );
        });
  }

  /// 选择 或者 拍照
  void _getImage(ImageSource source, int type) async {
    var image = await ImagePicker.pickImage(source: source);
    if (image == null) {
      return;
    }
    UserInfoDao.uploadToServerImage(image.path).then((value) {
      if (value.result) {
        if (type == 1) {
          _idCardFontImgServerStr = value.data;
          _idCardFontImgFile = image;
        } else if (type == 2) {
          _idCardBackImgServerStr = value.data;
          _idCardBackImgFile = image;
        } else {
          _idCardHandImgServerStr = value.data;
          _idCardHandImgFile = image;
        }
        setState(() {});
      }
    });
  }
}

///
///
///
///
///
///
///
class EditTextWidget extends StatefulWidget {
  ///
  ///
  /// [distance] 之间的距离
  ///
  EditTextWidget(
      {Key key,
      this.editName = '',
      this.textInputType,
      this.hintText,
      this.labelText,
      this.distance = 0.0,
      this.controller,
      this.onChanged})
      : super(key: key);

  final String editName;
  final TextInputType textInputType;
  final String hintText;
  final String labelText;
  final double distance;
  final TextEditingController controller;
  final ValueChanged<String> onChanged;

  @override
  _EditTextWidgetState createState() => _EditTextWidgetState();
}

class _EditTextWidgetState extends State<EditTextWidget> {
  TextEditingController editTextController;

  @override
  void initState() {
    editTextController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60.0,
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      margin: EdgeInsets.fromLTRB(0.0, 1.0, 0.0, 0.0),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(right: widget.distance),
            child: Text(widget.editName),
          ),
          Expanded(
            child: TextField(
              controller: editTextController,
              onChanged: widget.onChanged,
              keyboardType: widget.textInputType,
              style: TextStyle(color: Color(0xFF666666), fontSize: 12.0),
              decoration: InputDecoration(
                  hintText: widget.hintText,
                  labelText: widget.labelText,
                  hintStyle:
                      TextStyle(color: Color(0xFF999999), fontSize: 14.0),
                  disabledBorder: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none),
            ),
          ),
        ],
      ),
    );
  }
}

///
///
///
///
class CommonItemSelect extends StatelessWidget {
  CommonItemSelect({this.onTabItem, this.title, this.color, this.itemHeight});

  final String title;
  final Color color;
  final double itemHeight;
  final VoidCallback onTabItem;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTabItem,
      child: Container(
        margin: EdgeInsets.only(top: 1.0),
        color: Colors.white,
        alignment: Alignment.center,
        height: itemHeight,
        child: Text(
          title,
          style: TextStyle(
              color: color == null ? Colors.blue : color, fontSize: 16.0),
        ),
      ),
    );
  }
}

///
///  图片显示 Widget
///
class ImagePlaceHolder extends StatefulWidget {
  ImagePlaceHolder({this.placeholderAssetStr, this.imageFile, this.onTap})
      : assert(placeholderAssetStr != null);

  final File imageFile;
  final String placeholderAssetStr;
  final GestureTapCallback onTap;

  @override
  _ImagePlaceHolderState createState() => _ImagePlaceHolderState();
}

class _ImagePlaceHolderState extends State<ImagePlaceHolder> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.onTap,
      child: Container(
        child: Image(
          image: widget.imageFile == null
              ? AssetImage(widget.placeholderAssetStr)
              : FileImage(widget.imageFile),
          fit: BoxFit.cover,
        ),
        width: 200.0,
        height: 150.0,
      ),
    );
  }
}
